package net.bingosoft.common.util;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * Jun 18, 2008 12:41:54 PM
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:
 * ChangeLog:
 */
public class HttpClientUtil {
	private static final Log log = LogFactory.getLog(HttpClientUtil.class);

	private static String DEFAULT_REQUEST_HEADER = "application/x-www-form-urlencoded;charset=UTF-8";
	private static String DEFAULT_USER_AGET_ = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";



	public static String readContentFormURL(String url){
		String resoponseString = "";
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(url);
		client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); 
		method.setFollowRedirects(false);	//禁止自动跳转
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
		method.addRequestHeader("Content-Type", DEFAULT_REQUEST_HEADER);
		method.addRequestHeader("User-Agent", DEFAULT_USER_AGET_);
		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
					//重定向后的处理
					Header locationHeader = method.getResponseHeader("location");
					client.getParams().setParameter("http.socket.timeout", 60000 * 10);
					String redirectURL = locationHeader.getValue();
					method = new GetMethod(redirectURL);
					try {
						// Execute the method.
						int statusCode1 = client.executeMethod(method);
						if (statusCode1 != HttpStatus.SC_OK) {
							throw new Exception("get form data to url failed,statusCode:" + statusCode1);
						}
					} catch (IOException e) {
						throw e;
					}

				}
			}
			resoponseString = method.getResponseBodyAsString();

		} catch (Exception e) {
			throw new RuntimeException("读取URL 内容失败...",e);
		} finally {
			method.releaseConnection();
		}
		if(log.isDebugEnabled()){
			log.debug(resoponseString);
		}
		return resoponseString;
	}

	/**
	 * 提交表单数据到指定的url
	 * @param nameValuePair
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String postFormToURL(String url, Map<String,String> nameValuePair)  {
		String resultString = "";
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		client.getHttpConnectionManager().getParams().setConnectionTimeout(30000); 
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
		try {
			if (nameValuePair != null) {
				int mapSize = nameValuePair.size();
				NameValuePair[] nvps = new NameValuePair[mapSize];
				int index = 0;
				for (String key : nameValuePair.keySet()) {
					nvps[index] = new NameValuePair(key, nameValuePair.get(key));
					index ++;
				}
				postMethod.addRequestHeader("Content-Type", DEFAULT_REQUEST_HEADER);
				postMethod.addRequestHeader("User-Agent", DEFAULT_USER_AGET_);
				postMethod.setRequestBody(nvps);
			}
			int statusCode = client.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) {// 对重定向进行处理
				if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
					Header locationHeader = postMethod.getResponseHeader("location");
					String location = null;
					if (locationHeader != null) {
						location = locationHeader.getValue();
						if (log.isWarnEnabled()) {
							log.warn("The page was redirected to:" + location);
						}
						GetMethod method = new GetMethod(location);
						method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));

						method.addRequestHeader("Content-Type", DEFAULT_REQUEST_HEADER);
						method.addRequestHeader("User-Agent", DEFAULT_USER_AGET_);
						try {
							// Execute the method.
							int statusCode1 = client.executeMethod(method);
							if (statusCode1 != HttpStatus.SC_OK) {
								throw new Exception("post form data to url failed,statusCode:" + statusCode1);
							}
							resultString = method.getResponseBodyAsString();
						} catch (IOException e) {
							throw e;
						}
					} else {
						log.error("Method failed: " + postMethod.getStatusLine());
						throw new Exception("post form data to url failed");
					}
				}
			} else {
				resultString = postMethod.getResponseBodyAsString();
			}

		} catch (Exception e) {
			throw new RuntimeException("表单提交失败...",e);
		} finally {
			// Release the connection.
			postMethod.releaseConnection();
		}
		if (log.isDebugEnabled()) {
			log.debug(resultString);
		}
		return resultString;
	}

}
